package org.ctstudio.common.utils;

import java.util.*;

public class ListUtil {
  private static final int FENCHSIZE = 1000;

  public static <T> List<T> fromArray(T[] ary) {
    List<T> list = new ArrayList<T>(ary.length);
    for (T t : ary) {
      list.add(t);
    }
    return list;
  }

  public static <T> boolean isEmpty(List<T> list) {
    if (null == list || list.isEmpty()) {
      return true;
    }
    return false;
  }

  public static <T> boolean isNotEmpty(List<T> list) {
    return !isEmpty(list);
  }

  public static String toString(Iterable<?> list, Object connector) {
    if (list == null) {
      return null;
    }
    StringBuilder sb = new StringBuilder();
    for (Object o : list) {
      if (o != null) {
        if (sb.length() > 0) {
          sb.append(connector);
        }
        sb.append(o);
      }
    }
    return sb.toString();
  }

  public static String toString(Iterable<?> list) {
    return toString(list, ',');
  }

  /**
   * 把比较大的List集合分成一小份List集合
   * 
   * @param list
   * @return
   */
  public static <T> List<List<T>> fench(List<T> list) {
    List<List<T>> retList = new ArrayList<List<T>>();
    if (isNotEmpty(list)) {
      int pageSize = list.size() / FENCHSIZE + 1;
      if (0 == list.size() % FENCHSIZE) {
        pageSize--;
      }
      for (int i = 0; i < pageSize; i++) {
        if ((i + 1) * FENCHSIZE > list.size()) {
          retList.add(list.subList(i * FENCHSIZE, list.size()));
        } else {
          retList.add(list.subList(i * FENCHSIZE, (i + 1) * FENCHSIZE));
        }
      }
    }
    return retList;
  }

  /**
   * 向上转换
   * 
   * @param children
   * @return
   */
  public static <C extends F, F> List<F> listUp(List<C> children) {
    if (null == children) {
      return null;
    }
    List<F> parents = new ArrayList<F>();
    for (int i = 0; i < children.size(); i++) {
      parents.add(children.get(i));
    }
    return parents;
  }

  public static <T> List<List<T>> split(List<T> list, int size) {
    if (list == null || list.isEmpty() || size <= 0) {
      return Collections.emptyList();
    }
    if (size >= list.size()) {
      return Collections.singletonList(list);
    }
    int count = list.size() / size + (list.size() % size > 0 ? 1 : 0);
    List<List<T>> r = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      int fromIndex = i * size;
      int toIndex = Math.min((i + 1) * size, list.size());
      r.add(list.subList(fromIndex, toIndex));
    }
    return r;
  }
}
